'''
Created on Aug 12, 2010

@author: behrooz
'''
from django.contrib.admin.options import ModelAdmin
from django.contrib import admin
from django.utils.translation import ugettext as _
from amscms.payment.models import PaymentCredit, PaymentPolicy,\
    UserPaymentPolicy, PaymentCreditHistory, CreditDepositHistory

class PaymentCreditAdmin(ModelAdmin):
    list_display = ("id", "user", "balance", "last_modified")
    search_fields = ["user__username", "user__first_name", "user__last_name", "user__email"]
    
    def save_model(self, request, obj, form, change):
        old = PaymentCredit.objects.get(pk=obj.id)
        amount = obj.balance - old.balance
        if amount == 0:
            return
        history = CreditDepositHistory(credit=obj, amount=amount)
        history.save()
        obj.save()
    
class PaymentPolicyAdmin(ModelAdmin):
    list_display = ("id", "name", "isfree")

class UserPaymentPolicyAdmin(ModelAdmin):
    list_display = ("id", "user", "policy")
    
class PaymentCreditHistoryAdmin(ModelAdmin):
    actions = None
    list_display = ("id", "last_modified", "amount", "credit_advertizer", "order_ad", "order_amount")
    ordering = ("-last_modified", )
    list_filter = ("last_modified", )
    
    def credit_advertizer(self, obj):
        return obj.order.ad.advertizer.__unicode__()
    credit_advertizer.short_description = _("Advertizer")
    
    def order_ad(self, obj):
        return obj.order.ad.__unicode__()
    order_ad.short_description = _("Ad")
    
    def order_amount(self, obj):
        return str(obj.order.amount)
    order_amount.short_description = _("Amount") + " " + _("Ad Order")
    
    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        if obj is None:
            return True
        return False
    
class CreditDepositHistoryAdmin(ModelAdmin):
    actions = None
    list_display = ("id", "last_modified", "amount", "credit_user")
    ordering = ("-last_modified", )
    list_filter = ("last_modified", )
    
    def credit_user(self, obj):
        return obj.credit.user.get_full_name()
    credit_user.short_description = _("User")

    def has_add_permission(self, request):
        return False
    
    def has_change_permission(self, request, obj=None):
        if obj is None:
            return True
        return False
    
# Admin Registration
admin.site.register(PaymentCredit, PaymentCreditAdmin)
admin.site.register(PaymentPolicy, PaymentPolicyAdmin)
admin.site.register(UserPaymentPolicy, UserPaymentPolicyAdmin)
admin.site.register(PaymentCreditHistory, PaymentCreditHistoryAdmin)
admin.site.register(CreditDepositHistory, CreditDepositHistoryAdmin)
